<?php

$bgDirectory = 'pics';

$submitted = isset($_POST['index']);
$index = intval($_POST['index']);

$files = dirList($bgDirectory);

if($submitted) {
    // write index to the file
    $myFile = "nextBG.txt";
    $fh = fopen($myFile, 'w') or die("can't open file");
    $stringData = "" . $files[$index];
    fwrite($fh, $stringData);
    fclose($fh);
    //echo "received a submitted vote\n";
} else {
    //echo "going about on your regularly scheduled program\n";
}

function dirList ($directory) {
    // ************************** //
    $badfiles = array(".DS_Store", ".", "..");

    // create an array to hold directory list
    $results = array();

    // create a handler for the directory
    $handler = opendir($directory);

    // keep going until all files in directory have been read
    while ($file = readdir($handler)) {

        // if $file isn't in the bad list,
        // add it to the results array
        if (!in_array($file, $badfiles))
            $results[] = $file;
    }

    // tidy up: close the handler
    closedir($handler);

    // done!
    return $results;

}

$index = rand(0, sizeof($files)-1);
?>

<html>
<body bgcolor="black">

<?php if(!$submitted) { ?>
<form method="post" style="display: inline">
<input type="submit" style="height: 20%; width: 49%; font-size: 450%; background-color: green" value="Use Image" onclick="submit" />
<input type="hidden" name="index" value="<?php echo $index;?>">
</form>
<?php } ?>

<input type="button" style="height: 20%; width: <?php if($submitted) echo "95"; else echo "49"?>%; font-size: 450%; background-color: red;" value="Next Image" onclick="location.reload(true);" />

<img src="<?php if($submitted) echo "ThankYou.jpg"; else echo("pics/" . $files[$index]); ?>" width="100%" height="80%" alt="background" />

</body>
</html> 
